package com.shuatim.common.utils;

import com.shuatim.common.exception.ShuaTiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author : cookie ✌️
 * @date : 2018/11/13 11:06
 */
@Slf4j
public class FileUploadUtils {

    /**
     * @param file
     * @param module
     * @return
     */
    public static String writeUploadFile(MultipartFile file, String module) {
        if (null != file) {
            String fileName = file.getOriginalFilename();
            String realPath = "D:/ck/" + module + "/" + fileName;
            File fileDir = new File(realPath);
            // 获取文件的后缀名
            assert fileName != null;
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String allowImgFormat = ".gif,.jpg,.jpeg,.png";
            if (!allowImgFormat.contains(suffixName.toLowerCase())) {
                throw new ShuaTiException("文件格式不合法");
            }
            // 检测是否存在目录
            if (!fileDir.getParentFile().exists()) {
                fileDir.getParentFile().mkdirs();
            }
            try {
                file.transferTo(fileDir);
                return realPath;
            } catch (IOException e) {
                log.info("上传文件发生异常", e);
            }

        }
        return "上传图片失败";
    }
}
